 #include "weather.h"
#include "ui_weather.h"
#include <QJsonDocument>
#include <QFile>
weather::weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::weather)
{
    ui->setupUi(this);
    series_low = new QLineSeries();//创建连线对象
    series_hight = new QLineSeries();//创建连线对象
    chart = new QChart();
    item = new QStandardItemModel(2,15,ui->tableView);
    manager=new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}

weather::~weather()
{
    delete ui;
}
void weather::replyFinished(QNetworkReply * reply)//判断是否访问成功
{
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
        parseJson(reply->readAll());
    }
    else
    {
        qDebug()<<"匹配失败"<<endl;
    }
}

void weather::parseJson(QByteArray byteArray)//解析josn获取天气信息
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);
    QString day;
    QString temperature_hight;
    QString temperature_low;
    QString weath;
    QAbstractItemModel *model = ui->tableView->model(); // 获取模型
    if (model) {
        model->removeRows(0, model->rowCount());
    }
    if(doc.isObject())
    {
        qDebug()<<"该链接是一个对象"<<endl;
        QJsonObject obj1 = doc.object();
        if(obj1.contains("data"))
        {
            QJsonValue val=obj1.value("data");
            QJsonObject obj2 = val.toObject();
            if(obj2.contains("forecast"))
            {
                val = obj2.value("forecast");
                if(val.isArray())
                {
                    QJsonArray weather=val.toArray();
                    for (int i = 0; i < weather.size(); i++) // 从0开始，不用-0
                    {
                        QJsonObject obj = weather[i].toObject();

                        // 声明这些变量，更好地组织代码结构
                        QString temperature_hight;
                        QString temperature_low;
                        QString weath;
                        QString day;

                        // 获取JSON对象中的值
                        if (obj.contains("high"))
                        {
                            temperature_hight = obj.value("high").toString();
                        }
                        if (obj.contains("low"))
                        {
                            temperature_low = obj.value("low").toString();
                        }
                        if (obj.contains("type"))
                        {
                            weath = obj.value("type").toString();
                        }
                        if (obj.contains("ymd"))
                        {
                            day = obj.value("ymd").toString();
                        }

                        // 处理最高温度
                        QString highTempValue = temperature_hight.section(' ', 1, 1).remove("℃");
                           int highTempInt = highTempValue.toInt();
                           qDebug() << "High Temperature:" << highTempInt;

                           QString lowTempValue = temperature_low.section(' ', 1, 1).remove("℃");
                           int lowTempInt = lowTempValue.toInt();
                           qDebug() << "Low Temperature:" << lowTempInt;

                           series_hight->append(QPointF(i, highTempInt));
                           series_low->append(QPointF(i, lowTempInt));
                        // 将最低温度追加到序列中

                        // 添加天气图标
                        weather_pic(weath, i);

                        // 设置日期项
                        QStandardItem* item2 = new QStandardItem(day);
                        item->setItem(0, i, item2);
                    }

                    // 设置表格视图模型
                    ui->tableView->setModel(item);                    // 设置序列名称
                    series_low->setName("十五天最低温度");
                    series_hight->setName("十五天最高温度");

                    // 将序列添加到图表中
                    chart->addSeries(series_low);
                    chart->addSeries(series_hight);
                    chart->createDefaultAxes(); // 创建默认的XY轴
                    // 设置XY轴的标题
                    chart->axisX()->setTitleText("日期");
                    chart->axisY()->setTitleText("温度");

                    // 设置动画选项
                    chart->setAnimationOptions(QChart::AllAnimations);
                    this->ui->widget->setChart(chart);//把图表加进图表视图窗口

                }
            }
        }
    }
}

void weather::weather_pic(QString str,int i)//天气图标
{
    QStandardItem* item_1;
    item_1 = new QStandardItem();
    if(str=="晴")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/11.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
        if(i==0)
        {
            QMessageBox::about(this,"提示","请注意防晒");
        }
    }
    else if(str=="多云")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/12.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
    }
    else if(str=="阴")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/13.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
    }
    else if(str=="小雨")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/14.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
        if(i==0)
        {
            QMessageBox::about(this,"提示","有雨，出门记得带伞");
        }
    }
    else if(str=="中雨")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/15.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
        if(i==0)
        {
        QMessageBox::about(this,"提示","有雨，出门记得带伞");
}

    }
    else if(str=="大雨")
    {
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/16.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        item->setItem(1,i,item_1);
        if(i==0)
        {
        QMessageBox::about(this,"提示","雨很大不建议出门");

    }}

}

void weather::on_pushButton_clicked() //天气预报josn转换
{
    city_name=ui->lineEdit->text();
    file_open();
    manager->get(QNetworkRequest(QUrl(QString("http://t.weather.sojson.com/api/weather/city/%0").arg(city_num))));

}

void weather::file_open()//获取城市数据
{
    QFile file("D:/qtname/QT/QTchar/file/city.txt");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"file open error"<<endl;
    }
    QString numberPart;
    QString stringPart;
    QString line;
    int i=1;
    do{

        line = file.readLine();
        int firstSpaceIndex = line.indexOf('\t'); // 查找第一个空格的位置
        if (firstSpaceIndex != -1) {
            numberPart = line.left(firstSpaceIndex); // 提取数字部分
            stringPart = line.mid(firstSpaceIndex + 1).trimmed(); // 提取字符串部分，并去除前后空白
        }
        qDebug()<<numberPart<<stringPart<<city_name<<endl;
        i++;
        if(stringPart==city_name)
        {
            i=0;
            city_num=numberPart;
        }
    }while(i<2504&&i!=0);
}




//天气：晴&&温度超过30°，用小窗口提示温度太高记得做好防晒
//天气：雨，用小窗口提示出门记得带伞

